package com.tidy.seed.admin.system.controller;

import com.tidy.seed.admin.system.dto.file.upload.CreateDirDTO;
import com.tidy.seed.admin.system.dto.file.upload.DeletePathDTO;
import com.tidy.seed.admin.system.service.FileUploadService;
import com.tidy.seed.annotation.NoToken;
import com.tidy.seed.common.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * 系统模块 - 文件管理控制器
 */
@Api(tags = "文件上传")
@RestController
@RequestMapping("/admin/system/file")  // 路径增加 system 前缀，区分模块
public class FileUploadController {

    @Resource
    private FileUploadService fileUploadService;

    /**
     * 单文件上传
     */
    @ApiOperation("单文件上传")
    @NoToken
    @PostMapping(value = "/upload", consumes = "multipart/form-data")
    public Result uploadSingle(
            @RequestPart("file") MultipartFile file,
            @RequestPart(value = "dir", required = false) String dir
    ) {
        try {
            return Result.success(fileUploadService.uploadSingle(file, dir));
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 多文件上传
     */
    @ApiOperation("多文件上传")
    @NoToken
    @PostMapping("/uploads")
    public Result uploadMultiple(
            @RequestPart("files") List<MultipartFile> files,
            @RequestPart(value = "dir", required = false) String dir) {
        try {
            return Result.success(fileUploadService.uploadMultiple(files, dir));
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 逐级查询目录
     */
    @ApiOperation("逐级查询文件目录")
    @GetMapping("/dir")
    public Result listDir(
            @RequestParam(required = false, defaultValue = "") String currentPath
    ) {
        try {
            return Result.success(fileUploadService.listDir(currentPath));
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    @ApiOperation("删除文件或目录")
    @PostMapping("/deletePath")
    public Result deletePath(
            @RequestBody DeletePathDTO dto
    ) {
        try {
            fileUploadService.deletePath(dto.getTargetPath());
            return Result.success();
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    @ApiOperation("创建文件夹")
    @PostMapping("/createDir")
    public Result createDir(
            @RequestBody CreateDirDTO dto
    ) {
        try {
            fileUploadService.createDir(dto.getDirPath());
            return Result.success();
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }
}